package com.nsgf.library.ui.page;

import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;

import com.bumptech.glide.Glide;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.state.State;
import com.nsgf.library.BR;
import com.nsgf.library.R;
import com.nsgf.library.data.api.APIs;
import com.nsgf.library.data.bean.AnnouncementDetailBean;
import com.nsgf.library.data.bean.UserInfo;
import com.nsgf.library.data.bean.WorkOrderDetailBean;
import com.nsgf.library.data.response.ResponseStatus;
import com.nsgf.library.databinding.ActivityNoticeAnnouncementDetailBinding;
import com.nsgf.library.domain.request.AccountRequester;
import com.nsgf.library.glide.GlideImgManager;
import com.nsgf.library.photopicker.PhotoPreview;
import com.nsgf.library.photopicker.widget.MultiPickResultView;
import com.nsgf.library.utils.FileViewer;
import com.nsgf.skjz.utils.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 通知公告详情页面
 */
public class NoticeAnnouncementDetailActivity extends BaseActivity {

    private DetailStates mStates;
    private ActivityNoticeAnnouncementDetailBinding mBinding;
    private AccountRequester mAccountRequester;

    @Override
    protected void initViewModel() {
        mStates = getActivityScopeViewModel(DetailStates.class);
        mAccountRequester = getActivityScopeViewModel(AccountRequester.class);
    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {
        return new DataBindingConfig(R.layout.activity_notice_announcement_detail, BR.vm, mStates);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = (ActivityNoticeAnnouncementDetailBinding) getBinding();
        getLifecycle().addObserver(mAccountRequester);

        mStates.titleBar.set("公告详情");

        int noticeId = getIntent().getIntExtra("id", 0);
        String createTime = getIntent().getStringExtra("createTime");
        if (noticeId == 0) {
            ToastUtils.showLongToast("公告ID不能为空");
            finish();
            return;
        }

        // 获取详情数据
        mAccountRequester.getNoticeDetail(noticeId);
        mAccountRequester.getNoticeDetailResult().observe(this, new Observer<ResponseStatus<AnnouncementDetailBean>>() {
            @Override
            public void onChanged(ResponseStatus<AnnouncementDetailBean> responseStatus) {
                if (responseStatus.getResponseCode() == 200) {
                    AnnouncementDetailBean data = responseStatus.getData();
                    if (data != null) {
                        mBinding.setVmDetail(data);
                        mStates.detail.set(data);
                        
                        // 设置创建时间显示
                        if (createTime != null) {
                            mBinding.tvCreateTime.setText(createTime);
                            mBinding.tvCreateTime.setVisibility(View.VISIBLE);
                        } else if (data.getImageList() != null && !data.getImageList().isEmpty() 
                                && data.getImageList().get(0).getCreateTime() != null) {
                            mBinding.tvCreateTime.setText(data.getImageList().get(0).getCreateTime());
                            mBinding.tvCreateTime.setVisibility(View.VISIBLE);
                        } else {
                            mBinding.tvCreateTime.setVisibility(View.GONE);
                        }
                        
                        // 加载图片
                        if (data.getImageList() != null && !data.getImageList().isEmpty()) {
                            AnnouncementDetailBean.FileItem firstImage = data.getImageList().get(0);
                            if (firstImage != null && firstImage.getFilePath() != null) {
                                String imageUrl = APIs.BASE_URL_IMG + firstImage.getFilePath();
                                GlideImgManager.getInstance().glideCenterCrop(
                                        NoticeAnnouncementDetailActivity.this,
                                        imageUrl.replace("\\", "/"),
                                        mBinding.ivAnnouncementImage
                                );
                                mBinding.ivAnnouncementImage.setVisibility(View.VISIBLE);
                                
                                // 设置图片点击事件
                                mBinding.ivAnnouncementImage.setOnClickListener(v -> {
                                    ArrayList<WorkOrderDetailBean.FileDto> fileDtos = new ArrayList<>();
                                    for (AnnouncementDetailBean.FileItem item : data.getImageList()) {
                                        WorkOrderDetailBean.FileDto fileDto = new WorkOrderDetailBean.FileDto();
                                        fileDto.setFilePath(APIs.BASE_URL_IMG + item.getFilePath());
                                        fileDtos.add(fileDto);
                                    }
                                    PhotoPreview.builder()
                                            .setPhotos(fileDtos)
                                            .setAction(MultiPickResultView.ACTION_ONLY_SHOW)
                                            .start(NoticeAnnouncementDetailActivity.this);
                                });
                            } else {
                                mBinding.ivAnnouncementImage.setVisibility(View.GONE);
                            }
                        } else {
                            mBinding.ivAnnouncementImage.setVisibility(View.GONE);
                        }
                        
                        // 加载视频列表
                        updateVideoDisplay(data.getVideoList());
                        
                        // 加载文件列表
                        updateFileDisplay(data.getFileList());
                    }
                } else {
                    if (401 == responseStatus.getResponseCode()) {
                        UserInfo.getInstance().clearUserInfo();
                        finish();
                    } else {
                        ToastUtils.showLongToast(responseStatus.getMsg());
                    }
                }
            }
        });
    }

    /**
     * 更新视频显示
     */
    private void updateVideoDisplay(List<AnnouncementDetailBean.FileItem> videoList) {
        LinearLayout videoListLayout = mBinding.llVideoList;
        videoListLayout.removeAllViews();
        videoListLayout.setClipChildren(false);
        videoListLayout.setClipToPadding(false);

        if (videoList != null && !videoList.isEmpty()) {
            videoListLayout.setVisibility(View.VISIBLE);

            // 将dp转换为px
            float density = getResources().getDisplayMetrics().density;
            int videoSize = (int) (120 * density); // 120dp
            int playIconSize = (int) (32 * density); // 32dp
            int marginRight = (int) (10 * density); // 10dp

            for (AnnouncementDetailBean.FileItem video : videoList) {
                if (video == null || video.getFilePath() == null) {
                    continue;
                }

                // 创建视频预览视图容器
                RelativeLayout videoItemContainer = new RelativeLayout(this);
                RelativeLayout.LayoutParams containerParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                containerParams.setMargins(0, 0, marginRight, 0);
                videoItemContainer.setLayoutParams(containerParams);
                videoItemContainer.setClipChildren(false);
                videoItemContainer.setClipToPadding(false);

                // 视频缩略图
                ImageView thumbnail = new ImageView(this);
                RelativeLayout.LayoutParams thumbnailParams = new RelativeLayout.LayoutParams(
                        videoSize,
                        videoSize
                );
                thumbnail.setLayoutParams(thumbnailParams);
                thumbnail.setScaleType(ImageView.ScaleType.CENTER_CROP);
                thumbnail.setBackgroundResource(R.drawable.bg_upload_button);

                // 加载视频缩略图（网络路径）
                String videoUrl = APIs.BASE_URL_IMG + video.getFilePath();
                loadVideoThumbnail(thumbnail, videoUrl, videoSize);

                // 播放图标（居中显示）
                ImageView playIcon = new ImageView(this);
                RelativeLayout.LayoutParams playIconParams = new RelativeLayout.LayoutParams(
                        playIconSize,
                        playIconSize
                );
                playIconParams.addRule(RelativeLayout.CENTER_IN_PARENT);
                playIcon.setLayoutParams(playIconParams);
                playIcon.setImageResource(R.drawable.ic_play_circle_outline_white_48dp);
                playIcon.setBackgroundResource(android.R.color.transparent);

                // 点击事件 - 打开视频播放
                videoItemContainer.setOnClickListener(v -> {
                    // 使用 FileViewer 打开视频
                    FileViewer.openVideo(NoticeAnnouncementDetailActivity.this, videoUrl);
                });

                videoItemContainer.addView(thumbnail);
                videoItemContainer.addView(playIcon);
                videoListLayout.addView(videoItemContainer);
            }
        } else {
            videoListLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 更新文件显示
     */
    private void updateFileDisplay(List<AnnouncementDetailBean.FileItem> fileList) {
        LinearLayout fileListLayout = mBinding.llFileList;
        fileListLayout.removeAllViews();

        if (fileList != null && !fileList.isEmpty()) {
            fileListLayout.setVisibility(View.VISIBLE);

            float density = getResources().getDisplayMetrics().density;
            int padding = (int) (12 * density);
            int marginTop = (int) (8 * density);

            for (AnnouncementDetailBean.FileItem file : fileList) {
                if (file == null || file.getFilePath() == null) {
                    continue;
                }

                // 创建文件项视图
                LinearLayout fileItem = new LinearLayout(this);
                fileItem.setOrientation(LinearLayout.HORIZONTAL);
                fileItem.setPadding(padding, padding, padding, padding);
                fileItem.setBackgroundResource(R.drawable.bg_upload_button);
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT
                );
                params.setMargins(0, marginTop, 0, 0);
                fileItem.setLayoutParams(params);

                // 文件图标（如果没有 ic_file，使用文本代替）
                TextView fileIcon = new TextView(this);
                int iconSize = (int) (24 * density);
                LinearLayout.LayoutParams iconParams = new LinearLayout.LayoutParams(iconSize, iconSize);
                iconParams.gravity = android.view.Gravity.CENTER_VERTICAL;
                fileIcon.setLayoutParams(iconParams);
                fileIcon.setText("📄");
                fileIcon.setTextSize(20);
                fileIcon.setGravity(android.view.Gravity.CENTER);

                // 文件名
                TextView fileName = new TextView(this);
                LinearLayout.LayoutParams nameParams = new LinearLayout.LayoutParams(
                        0,
                        LinearLayout.LayoutParams.WRAP_CONTENT,
                        1.0f
                );
                nameParams.setMargins((int) (12 * density), 0, 0, 0);
                nameParams.gravity = android.view.Gravity.CENTER_VERTICAL;
                fileName.setLayoutParams(nameParams);
                fileName.setText(file.getFileName() != null ? file.getFileName() : "未知文件");
                fileName.setTextColor(getResources().getColor(R.color.color_495662));
                fileName.setTextSize(14);
                fileName.setMaxLines(1);
                fileName.setEllipsize(android.text.TextUtils.TruncateAt.END);

                // 浏览器图标按钮
                TextView browserIcon = new TextView(this);
                int browserIconSize = (int) (24 * density);
                LinearLayout.LayoutParams browserParams = new LinearLayout.LayoutParams(browserIconSize, browserIconSize);
                browserParams.gravity = android.view.Gravity.CENTER_VERTICAL;
                browserParams.setMargins((int) (8 * density), 0, 0, 0);
                browserIcon.setLayoutParams(browserParams);
                browserIcon.setText("🌐");
                browserIcon.setTextSize(18);
                browserIcon.setGravity(android.view.Gravity.CENTER);
                browserIcon.setPadding((int) (4 * density), 0, (int) (4 * density), 0);
                browserIcon.setClickable(true);
                browserIcon.setFocusable(true);

                // 文件URL - 处理路径中的反斜杠，确保是完整的网络URL
                String filePath = file.getFilePath();
                if (filePath != null) {
                    filePath = filePath.replace("\\", "/");
                    // 确保路径以 / 开头（如果BASE_URL_IMG不以/结尾，则需要）
                    if (!filePath.startsWith("/")) {
                        filePath = "/" + filePath;
                    }
                }
                // 构建完整的网络URL
                String baseUrl = APIs.BASE_URL_IMG;
                if (baseUrl == null) {
                    baseUrl = "";
                }
                // 移除baseUrl末尾的斜杠（如果有）
                if (baseUrl.endsWith("/")) {
                    baseUrl = baseUrl.substring(0, baseUrl.length() - 1);
                }
                // 确保filePath以/开头
                if (filePath != null && !filePath.startsWith("/")) {
                    filePath = "/" + filePath;
                }
                final String fileUrl = baseUrl + (filePath != null ? filePath : "");

                // 点击文件名 - 使用 FileViewer 打开文件
                fileName.setOnClickListener(v -> {
                    // 确保是完整的网络URL
                    if (fileUrl != null && !fileUrl.startsWith("http://") && !fileUrl.startsWith("https://")) {
                        // 如果BASE_URL_IMG为空或格式不对，提示错误
                        ToastUtils.showLongToast("文件URL格式错误");
                        return;
                    }
                    FileViewer.openFile(NoticeAnnouncementDetailActivity.this, fileUrl);
                });

                // 点击浏览器图标 - 在浏览器中打开文件
                browserIcon.setOnClickListener(v -> {
                    openUrlInBrowser(fileUrl);
                });

                fileItem.addView(fileIcon);
                fileItem.addView(fileName);
                fileItem.addView(browserIcon);
                fileListLayout.addView(fileItem);
            }
        } else {
            fileListLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 加载视频缩略图（支持网络路径）
     */
    private void loadVideoThumbnail(ImageView imageView, String videoUrl, int size) {
        // 如果是网络路径，使用 Glide 加载（Glide 可以自动处理视频缩略图）
        if (videoUrl.startsWith("http://") || videoUrl.startsWith("https://")) {
            Glide.with(this)
                    .asBitmap()
                    .load(videoUrl)
                    .placeholder(R.drawable.bg_upload_button)
                    .error(R.drawable.bg_upload_button)
                    .override(size, size)
                    .centerCrop()
                    .into(imageView);
        } else {
            // 本地路径，使用 MediaMetadataRetriever
            new Thread(() -> {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                try {
                    retriever.setDataSource(videoUrl);
                    Bitmap bitmap = retriever.getFrameAtTime(0, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
                    if (bitmap != null) {
                        runOnUiThread(() -> {
                            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
                            imageView.setImageBitmap(scaledBitmap);
                            if (scaledBitmap != bitmap) {
                                bitmap.recycle();
                            }
                        });
                    }
                } catch (Exception e) {
                    Log.e("NoticeAnnouncementDetail", "加载视频缩略图失败: " + e.getMessage());
                } finally {
                    try {
                        retriever.release();
                    } catch (Exception e) {
                        Log.e("NoticeAnnouncementDetail", "释放MediaMetadataRetriever失败: " + e.getMessage());
                    }
                }
            }).start();
        }
    }

    public static class DetailStates extends StateHolder {
        public final State<String> titleBar = new State<>("公告详情");
        public final State<AnnouncementDetailBean> detail = new State<>(null);
    }
}

